package com.third.customer.service.client;

import com.third.customer.service.data.UserLoginData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Optional;

/**
 * Created by hehuaichun on 2020/5/20.
 */
@Component
@Slf4j
public class RedisClient {

    @Autowired
    private JedisPool jedisPool;

    private final static String LOGIN = "LOGIN";

    private final static String SPLIT = "-";

    @Value("${user.login.timeout.minutes}")
    private long loginTimeoutMinutes = 30;

    public String setLoginToken(Long companyId, String userName, String token, boolean first) {
        String key = format(LOGIN, token);
        String value = format(companyId, userName);
        String nxxx = first ? "NX" : "XX";
        Jedis jedis = jedisPool.getResource();
        String status = "";
        try {
            status = jedis.set(key, value, nxxx, "EX", loginTimeoutMinutes * 60);
        } finally {
            jedisPool.returnResource(jedis);
        }
        return status;
    }

    public boolean removeLoginToken(String token) {
        Jedis jedis = jedisPool.getResource();
        boolean success;
        try {
            success = jedis.del(format(LOGIN, token)) > 0;
        } finally {
            jedisPool.returnResource(jedis);
        }
        return success;
    }

    public Optional<UserLoginData> getLoginUserPair(String token) {
        Jedis jedis = jedisPool.getResource();
        UserLoginData userLoginData = null;
        try {
            String pairString = jedis.get(format(LOGIN, token));
            if (StringUtils.isEmpty(pairString)) {
                return Optional.empty();
            }
            userLoginData = parseUser(pairString);
        } finally {
            jedisPool.returnResource(jedis);
        }
        return Optional.ofNullable(userLoginData);
    }

    private String format(Object prefix, Object suffix) {
        return prefix + SPLIT + suffix;
    }

    private UserLoginData parseUser(String companyIdUserName) {
        String[] strings = companyIdUserName.split(SPLIT);
        try {
            return new UserLoginData(Long.valueOf(strings[0]), strings[1]);
        } catch (Exception e) {
            log.error("failed to parse companyIdUserName [{}]", companyIdUserName);
            return null;
        }
    }

}

